#include "main.h"

// 4 Keys: Menu, Up, Down, Enter
bool pinMenu_now, pinUp_now, pinDown_now, pinEnter_now;
bool pinMenu_last, pinUp_last, pinDown_last, pinEnter_last;
uint32_t menu_cnt, up_cnt, down_cnt, enter_cnt;
uint8_t portStatus;
bool menu_short;
bool enter_short;
bool up_short;
bool down_short;

// Mode Setting
uint32_t mode_cnt = 0;
uint8_t mode = MODE_IDLE;

void key_init(void)
{
	// Initialize the key input without pull-up
	GPIO_Init(KEY_PORT, KEY_MENU|KEY_UP|KEY_DOWN|KEY_ENTER, GPIO_MODE_IN_FL_NO_IT);

	// only interrupt on falling edge
	//EXTI_SetExtIntSensitivity(EXTI_PORT_GPIOB, EXTI_SENSITIVITY_FALL_ONLY);

	menu_cnt = 0;
	enter_cnt = 0;
	up_cnt = 0;
	down_cnt = 0;

	menu_short = FALSE;
	down_short = FALSE;
	up_short   = FALSE;
	enter_short = FALSE;

	mode = MODE_IDLE;
}

void key_scan(void)  // Refresh in 20ms
{

	portStatus = 0xFF - GPIO_ReadInputData(KEY_PORT);
	menu_short  = portStatus & KEY_MENU;
	up_short    = portStatus & KEY_UP;
	down_short  = portStatus & KEY_DOWN;
	enter_short = portStatus & KEY_ENTER;

	switch(mode) {

		case MODE_IDLE:
			if (menu_short) {
				mode = MODE_MENU;
				ShowMenu();
			}else if (up_short) {
				if (activeRecord<sensor_save_cnt)
					activeRecord++;
				ShowRecord(activeRecord);
			}else if (down_short) {
				if (activeRecord>3)
					activeRecord--;
				ShowRecord(activeRecord);
			}else if (enter_short) {

			}
			menu_short = FALSE;
			up_short = FALSE;
			down_short = FALSE;
			enter_short = FALSE;
			break;

		case MODE_MENU:
			if (menu_short) {
				mode = MODE_IDLE;
				ShowRecord(activeRecord);
			}else if (enter_short) {
				eeprom_clear_data();
				ShowClearData();
				delay(50000);
				mode = MODE_IDLE;
				activeRecord = 0;
				ShowRecord(activeRecord);
			}
			menu_short = FALSE;
			up_short = FALSE;
			down_short = FALSE;
			enter_short = FALSE;
			break;

		default:
			break;
	}

	pinMenu_last = pinMenu_now;
	pinUp_last = pinUp_now;
	pinDown_last = pinDown_now;
	pinEnter_last = pinEnter_now;
}


void key_test(void)
{

	portStatus = 0xFF - GPIO_ReadInputData(KEY_PORT);
	menu_short  = portStatus & KEY_MENU;
	up_short    = portStatus & KEY_UP;
	down_short  = portStatus & KEY_DOWN;
	enter_short = portStatus & KEY_ENTER;

	if (menu_short) {
		lcd_set_row(0);
		lcd_print("Menu            ");
		menu_short = FALSE;
	}

	if (up_short) {
		lcd_set_row(0);
		lcd_print("Up              ");
		up_short = FALSE;
	}

	if (down_short) {
		lcd_set_row(0);
		lcd_print("Down            ");
		down_short = FALSE;
	}

	if (enter_short) {
		lcd_set_row(0);
		lcd_print("Enter           ");
		enter_short = FALSE;
	}

}